/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.dusin.teachassist.servlet.teacher;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.dusin.teachassist.util.DownLoadUtils;
import org.dusin.teachassistdbservice.util.TheUtil;

/**
 *
 * @author dusin
 */
@WebServlet(name = "Download", urlPatterns = {"/servlet/teacher/Download"})
public class Download extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //response.setContentType("text/json;charset=UTF-8");
        //PrintWriter out = response.getWriter();
        
        ServletContext servletContext = request.getServletContext();
        ServletOutputStream out=null;
        PrintWriter pw = null;
        StringBuilder sbDirectory= new StringBuilder();
        boolean seccess = true;
        String msg = "";
        String jsonResult="";
        String dataDirectoryStr = servletContext.getInitParameter("DataDirectory");
        //System.out.println("++++"+dataDirectoryStr);
        if(dataDirectoryStr==null){
            sbDirectory.append( "e:/ta");
        }else{
            sbDirectory.append(dataDirectoryStr);
        }
        HttpSession session = request.getSession();
        String teacherNo = (String)session.getAttribute("teacherNo");
        String semester = (String)session.getAttribute("semester");
        String courseName =(String)session.getAttribute("courseName");
        sbDirectory.append("/").append(teacherNo).append("/").append(semester).append("/").append(courseName);
        String type = request.getParameter("type");
        if("1".equals(type)){
            sbDirectory.append("/实验/");
        }else{
            sbDirectory.append("/作业/");
        }
        String no = request.getParameter("no");
        sbDirectory.append(no).append("/");
        String fileName = request.getParameter("fileName");
        sbDirectory.append(fileName);        
         //System.out.println(sbDirectory.toString());
        try {
           if(!new File(sbDirectory.toString()).exists()){
               msg = "文件不存在";
               throw new Exception(msg);
           }else{
               out = response.getOutputStream();
               String filename = sbDirectory.toString();
              
               String mimeType = servletContext.getMimeType(filename);//获取文件的mime类型
               //BufferedReader fis =new BufferedReader( new FileReader(filename));//输入流
               FileInputStream fis = new FileInputStream(filename);//输入流
               response.setHeader("content-type",mimeType);
               System.out.println(mimeType);
               //解决中文乱码问题
                //1.获取user-agent请求头
                String agent = request.getHeader("user-agent");

                //2.使用工具类方法编码文件名即可
                fileName  = DownLoadUtils.getFileName(agent, fileName);
                //3.2设置响应头打开方式 content-disposition      千万不能写错
                response.setHeader("content-disposition", "attachment;filename="+ fileName);

                //4.将输入流的数据写出到输出流中
                //ServletOutputStream sos = response.getOutputStream();//首先需要一个输出流
                byte[] buff = new byte[1024 * 8];//其次需要一个字节数组作为缓冲区
                int len = 0;    //代表读到的字节的个数
                while ((len = fis.read(buff))!= -1){//把输入流中的字节读到缓冲区，并且把读到的个数赋值给len，如果没有读取到文件的末尾
                    out.write(buff, 0, len);//输出流不停的往外写，因为是字节流，所以不用刷新。这里掌握不充分，知识点都不记得了
                }
                fis.close();
           }
        }catch(Exception e){
            pw = response.getWriter();
            jsonResult = TheUtil.getJsonResult(false, msg);
            out.println(jsonResult);
        }finally {
            if(pw!=null){
                pw.close();
            }
            if(out!=null)
                out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
